package ua.com.fesvlast.hotel.model.commands;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ua.com.fesvlast.hotel.controller.managers.ConfigurationManager;
import ua.com.fesvlast.hotel.controller.managers.MessageManager;
import ua.com.fesvlast.hotel.model.dao.DAOFactory;
import ua.com.fesvlast.hotel.model.enteties.Orders;
import ua.com.fesvlast.hotel.model.enteties.Users;
import ua.com.fesvlast.hotel.model.utils.DateFormatter;
import ua.com.fesvlast.hotel.model.utils.OrderStatus;

public class MakeOrderCommand implements ICommand {

	@Override
	public String execute(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
		String page =null;
		String arrivalDate=request.getParameter("arrivalDate");
		String departureDate=request.getParameter("departureDate");
		String commentTextAreaOrder=request.getParameter("comment");
		int roomId=Integer.valueOf(request.getParameter("roomId"));
		Users currentUser =(Users)request.getSession().getAttribute("currentUser");
		int userId=currentUser.getUserId();
		
		Orders order =new Orders();
		order.setArrivalTime(arrivalDate);
		order.setComment(commentTextAreaOrder);
		order.setDepartureTime(departureDate);
		order.setHotelRoomId(roomId);
		order.setOrderDate(DateFormatter.getCurrentFormatDate());
		order.setUserId(userId);
		order.setStatus(OrderStatus.OPENED.toString());
		
		int orderId=DAOFactory.getOrdersDAO().createOrder(order);
		if(orderId==-1){
			request.setAttribute("errorMessage", MessageManager.getInstance().getProperty(MessageManager.ORDER_ERROR_MESSAGE));
			page=ConfigurationManager.getInstance().getProperty(ConfigurationManager.ERROR_PAGE_PATH);		
		}
		if(orderId>0){
			String message = MessageManager.getInstance().getProperty(MessageManager.ORDER_APPLICATION);
			request.setAttribute("message", message );
			page=ConfigurationManager.getInstance().getProperty(ConfigurationManager.MAIN_PAGE_PATH);
		}else{
			
			request.setAttribute("errorMessage", MessageManager.getInstance().getProperty(
					MessageManager.SERVLET_EXCEPTION_ERROR_MESSAGE));
			
			page=ConfigurationManager.getInstance().getProperty(
					ConfigurationManager.ERROR_PAGE_PATH);
		}
		return page;
	}

}
